Step 4: Bookmark DAO

Create a subfolder data inside the src folder. Add the file BookmarkDAO.js to the data subfolder with the following content:

import Bookmark from "../model/Bookmark";

class BookmarkDAO {

  // return the created bookmark
  create({ title, url }) {
    
  }

  // return all bookmarks
  readAll() {
    
  }

  // return the bookmark with the given ID
  // return undefined if no bookmark exists with the given ID  
  read(id) {
    
  }

  // update a bookmark given its ID
  // return the updated bookmark
  // return undefined if no bookmark exists with the given ID
  update({ id, title, url }) {
    
  }

  // delete a bookmark given its ID
  // return the deleted bookmark 
  // return undefined if no bookmark exists with the given ID
  delete(id) {
    
  }
}

export default BookmarkDAO;

Notice that BookmarkDAO provides CRUD operations. This class is a Data Access Object (DAO) for Bookmark.

In a nutshell, a DAO is an object that provides an abstraction over some database or other persistence mechanisms.

We will eventually store the notes in a database. For now, however, let's store them in an array! Add a constructor to the BookmarkDAO class:

  constructor() {
    this.bookmarks = [];
  }

Let’s provide an implementation for all the operations of the BookmarkDAO class.

Implement the create operation as follows:

  // return the created bookmark
  create({ title, url }) {
    const bookmark = new Bookmark(title, url);
    this.bookmarks.push(bookmark);
    return bookmark;
  }

Implement the readAll operation as follows:

  // return all bookmarks
  readAll() {
    return this.bookmarks;
  }

Implement the read operation as follows:

  // return the bookmark with the given id
  // return undefined if no bookmark exists with the given ID
  read(id) {
    return this.bookmarks.find((bookmark) => bookmark.id === id);
  }

Implement the update operation as follows:

  // update a bookmark given its ID  
  // return the updated bookmark
  // return undefined if no bookmark exists with the given ID
  update({ id, title, url }) {
    const bookmark = this.read(id);
    if (bookmark) {
      title && (bookmark.title = title);
      url && (bookmark.url = url);
    }
    return bookmark;
  }

Implement the delete operation as follows:

  // delete a bookmark given its ID
  // return the deleted bookmark
  // return undefined if no bookmark exists with the given ID
  delete(id) {
    const index = this.bookmarks.findIndex((bookmark) => bookmark.id === id);
    const bookmark = this.bookmarks[index];
    this.bookmarks.splice(index, 1);

    return bookmark;
  }

Note we have not considered cases where the input to any of these operations is invalid. We will deal with error handling later!

Save and commit the changes.